package org.biogroovy.io.local

import javax.xml.parsers.DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory

import org.biogroovy.io.AbsReader
import org.biogroovy.io.IFetcher;
import org.biogroovy.models.RSSFeed
import org.w3c.dom.Node

/**
 * 
 *
 */
class RSSReader extends AbsReader<RSSFeed, Node> {


	@Override
	public RSSFeed read(InputStream inputStream) throws IOException {
		def factory = DocumentBuilderFactory.newInstance();
				
		factory.setNamespaceAware(false);
		factory.setValidating(false);
		factory.setFeature("http://xml.org/sax/features/namespaces", false);
		factory.setFeature("http://xml.org/sax/features/validation", false);
		factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
		factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
		factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false)
		
		DocumentBuilder builder  = factory.newDocumentBuilder();
		Node root     = (Node)builder.parse(inputStream).documentElement

		println "xml: " + root
		RSSFeed feed = new RSSFeed();
		return parse(feed, root);
	}

	@Override
	public void parse(RSSFeed feed, Node node) {
		feed.iconUrl = node.@iconUrl;
		feed.url = node.@url;
		feed.name = node.@name;
		feed.description = node.description[0].text();
		node.tag.each { tagNode ->
			feed.tagSet.add(tagNode.@name);
		}
	}

	@Override
	public List<RSSFeed> readList(InputStream inputStream) throws IOException {
		def xml = new XmlParser().parse(inputStream);
		List<RSSFeed> feedList = new ArrayList<>();
		
		xml.feeds.rss.each{Node rssNode ->
			RSSFeed feed = new RSSFeed()
			parse(feed, rssNode);
			feedList.add(feed)
		}
		
		return feedList;
	}


	@Override
	public RSSFeed fetch(String id) throws IOException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public URL getUrl(String id, Map<String, String> paramMap) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getDatabaseName() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<RSSFeed> fetchAll(String id) throws IOException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public IFetcher<RSSFeed> getNewInstance() {
		return new RSSReader();
	}

}
